package net.aias.springaichat.adapter.openapi;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @Auther: cheng.tang
 * @Date: 2025/4/29
 * @Description: spring-ai-chat
 */
@RestController
@RequestMapping("/api/chat")
@Slf4j
@CrossOrigin(origins = "*") // 添加跨域支持
public class ChatController {
    @Autowired
    private ChatClient chatClient; // 直接注入 ChatClient

    // 普通 REST 接口
    @GetMapping("/query")
    public String query(@RequestParam String query) {
        try {
            String response = chatClient.prompt().user(query).call().content();
            log.info("Response: {}", response);
            return response;
        } catch (Exception e) {
            log.error("Error processing query", e);
            return "Error: " + e.getMessage();
        }
    }


    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestParam String query) {
        log.info("Received query: {}", query);
        return chatClient.prompt()
                .advisors(new SimpleLoggerAdvisor()) // add log
                .user(query)
                .stream()
                .content()
                .map(content -> {
                    // 标准化列表格式
                    log.info("Stream content: {}", content);
                    return content
                            .replaceAll("^- ", "* ")  // 统一列表符号
                            .replaceAll("\n- ", "\n* ");  // 追加换行符
                })
                .concatWith(Flux.just("[DONE]\n"))  // 结束标记
                .onErrorResume(e -> {
                    log.error("Stream error: {}", e.getMessage());
                    return Flux.just("服务暂时不可用，请稍后再试\n[DONE]\n");
                });
    }


}
